let createError = require("http-errors");
let express = require("express");
let path = require("path");
let cookieParser = require("cookie-parser");
let logger = require("morgan");
// swagger
const swaggerUi = require("swagger-ui-express");
const swaggerJSDoc = require("swagger-jsdoc");
// 添加CORS中间件
const cors = require("cors");

require("dotenv").config();

let app = express();

// 全局CORS配置
app.use(
  cors({
    // origin: (origin, callback) => {
    //   console.log(origin, "origin");
    //   // 默认允许的来源白名单
    //   const whitelist = [
    //     "http://localhost:8000", // Umi/React dev server
    //     "http://localhost:5173", // Vite dev server
    //     "http://localhost:528", // Your specified port
    //   ];
    //   // 如果请求来源在白名单中，或者请求不是来自浏览器（例如 Postman, Apifox）
    //   if (whitelist.includes(origin) || !origin) {
    //     callback(null, true);
    //   } else {
    //     callback(new Error("Not allowed by CORS"));
    //   }
    // },
    origin: "*",
    methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
    allowedHeaders: ["Content-Type", "Authorization", "Access_token", "token"],
    credentials: true,
  })
);

// 启动邮件消费者
// const { mailConsumer } = require("./utils/rabbit-mq");
// (async () => {
//   await mailConsumer();
// })();

// 启动定时任务
// const initScheduleTasks = require("./tasks");
// initScheduleTasks();

const swaggerJSDocOptions = {
  definition: {
    openapi: "3.0.0",
    info: {
      title: "晁阳",
      version: "1.0.0",
    },
  },
  // apis: ["./routes/admin/*.js"], // 包含接口说明、注释的文件路径
  apis: ["./docs/front/*.yaml", "./docs/admin/*.yaml"],
};
const swaggerSpec = swaggerJSDoc(swaggerJSDocOptions);

const swaggerUiOptions = {
  explorer: true,
};
app.use(
  "/api-docs",
  swaggerUi.serve,
  swaggerUi.setup(swaggerSpec, swaggerUiOptions)
);

// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "jade");

app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));

// 路由
const routes = require("./config/routes");
app.use(routes);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render("error");
});

module.exports = app;
